<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Message } from '@arco-design/web-vue'
import { getUserOrders, payOrder, cancelOrder } from '@/api/order'
import { getDishById } from '@/api/dish'
import type { Order } from '@/api/order'
import type { Dish } from '@/api/dish'
import type { ApiResponse } from '@/api/user'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const loading = ref(false)
const orders = ref<Array<Order & { dishes?: Dish[] }>>([])
const paymentVisible = ref(false)
const currentOrderNo = ref('')
const selectedPayMethod = ref(1) // 默认微信支付

// 支付方式选项
const payMethodOptions = [
  { label: '微信支付', value: 1 },
  { label: '支付宝支付', value: 2 },
  { label: '余额支付', value: 3 }
]

// 加载订单数据
const loadOrders = async () => {
  loading.value = true
  orders.value = [] // 清空现有订单
  
  try {
    // 获取用户订单列表
    const userStore = useUserStore();
    if (!userStore.isLoggedIn) {
      Message.warning('请先登录')
      router.push('/login?redirect=/order')
      return
    }
    
    const userId = userStore.currentUser?.id;
    if (!userId) {
      throw new Error('用户ID不存在')
    }
    
    const orderListRes = await getUserOrders(userId)
    console.log('订单API返回数据:', orderListRes)
    
    if (orderListRes.code === 200 && orderListRes.data) {
      // 检查返回的数据结构
      let orderList: Order[] = [];
      
      if (Array.isArray(orderListRes.data)) {
        // 如果直接是数组
        orderList = orderListRes.data;
      } else if (typeof orderListRes.data === 'object' && orderListRes.data !== null) {
        // 如果是分页对象，尝试获取content属性
        const pageData = orderListRes.data as any;
        if (pageData.content && Array.isArray(pageData.content)) {
          orderList = pageData.content;
        }
      }
      
      console.log('处理后的订单列表:', orderList);
      
      // 不再单独获取菜品信息，直接使用orderItems中的dishName
      for (const order of orderList) {
        orders.value.push(order)
      }
      
      console.log('成功获取订单列表:', orders.value)
    } else {
      throw new Error(orderListRes.message || '获取订单列表失败')
    }
  } catch (error) {
    console.error('加载订单数据失败:', error)
    Message.error('加载订单数据失败，请稍后再试')
  } finally {
    loading.value = false
  }
}

// 刷新订单列表
const refreshOrders = () => {
  loadOrders()
  Message.success('刷新成功')
}

// 初始化数据
onMounted(() => {
  loadOrders()
})

// 打开支付对话框
const openPaymentDialog = (orderNo: string) => {
  currentOrderNo.value = orderNo
  selectedPayMethod.value = 1 // 默认选择微信支付
  paymentVisible.value = true
}

// 关闭支付对话框
const closePaymentDialog = () => {
  paymentVisible.value = false
  currentOrderNo.value = ''
}

// 支付订单
const handlePayOrder = async () => {
  if (!currentOrderNo.value) {
    Message.error('订单号不能为空')
    return
  }
  
  try {
    const payRes = await payOrder(currentOrderNo.value, selectedPayMethod.value)
    if (payRes.code === 200) {
      Message.success('支付成功')
      
      // 关闭支付对话框
      closePaymentDialog()
      
      // 直接更新当前订单的状态，而不是重新加载所有订单
      const orderIndex = orders.value.findIndex(order => order.orderNo === currentOrderNo.value)
      if (orderIndex !== -1) {
        // 更新订单状态为"已支付"
        orders.value[orderIndex].status = 1
        orders.value[orderIndex].payTime = new Date().toISOString()
        orders.value[orderIndex].payMethod = selectedPayMethod.value
        
        console.log('订单状态已更新:', orders.value[orderIndex])
      }
      
      // 延迟一秒后再刷新订单列表，确保后端数据已更新
      setTimeout(() => {
        loadOrders()
      }, 1000)
    } else {
      throw new Error(payRes.message || '支付失败')
    }
  } catch (error) {
    console.error('支付订单失败:', error)
    Message.error('支付订单失败，请稍后再试')
  }
}

// 取消订单
const handleCancelOrder = async (orderNo: string) => {
  try {
    const cancelRes = await cancelOrder(orderNo)
    if (cancelRes.code === 200) {
      Message.success('订单已取消')
      
      // 直接更新当前订单的状态，而不是重新加载所有订单
      const orderIndex = orders.value.findIndex(order => order.orderNo === orderNo)
      if (orderIndex !== -1) {
        // 更新订单状态为"已取消"
        orders.value[orderIndex].status = 6
        
        console.log('订单状态已更新为已取消:', orders.value[orderIndex])
      }
      
      // 延迟一秒后再刷新订单列表，确保后端数据已更新
      setTimeout(() => {
        loadOrders()
      }, 1000)
    } else {
      throw new Error(cancelRes.message || '取消订单失败')
    }
  } catch (error) {
    console.error('取消订单失败:', error)
    Message.error('取消订单失败，请稍后再试')
  }
}

// 查看订单详情
const viewOrderDetail = (orderId: number) => {
  router.push(`/order/${orderId}`)
}

// 获取订单状态文本
const getOrderStatusText = (status?: number) => {
  switch (status) {
    case 0:
      return '待支付'
    case 1:
      return '已支付'
    case 2:
      return '已接单'
    case 3:
      return '已完成'
    case 4:
      return '已取消'
    default:
      return '未知状态'
  }
}

// 获取订单状态颜色
const getOrderStatusColor = (status?: number) => {
  switch (status) {
    case 0:
      return 'orange'
    case 1:
      return 'blue'
    case 2:
      return 'purple'
    case 3:
      return 'green'
    case 4:
      return 'red'
    default:
      return 'gray'
  }
}

// 获取支付方式文本
const getPayMethodText = (payMethod?: number) => {
  switch (payMethod) {
    case 1:
      return '微信支付'
    case 2:
      return '支付宝支付'
    case 3:
      return '余额支付'
    default:
      return '未知支付方式'
  }
}

// 格式化日期时间
const formatDateTime = (dateStr?: string) => {
  if (!dateStr) return ''
  
  try {
    const date = new Date(dateStr)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
  } catch (e) {
    return dateStr
  }
}

// 返回首页
const goToHome = () => {
  router.push('/')
}
</script>

<template>
  <div class="order-container">
    <a-spin :loading="loading" tip="加载中...">
      <!-- 标题栏 -->
      <div class="order-header">
        <h2>我的订单</h2>
        <div class="header-actions">
          <a-button type="outline" @click="refreshOrders">
            <template #icon><i class="icon-refresh"></i></template>
            刷新
          </a-button>
          <a-button type="outline" @click="goToHome">返回首页</a-button>
        </div>
      </div>

      <!-- 订单列表 -->
      <div class="order-list">
        <a-empty v-if="orders.length === 0" description="暂无订单" />
        <a-card
          v-for="order in orders"
          :key="order.id || order.orderNo"
          class="order-card"
          :bordered="false"
        >
          <div class="order-top">
            <div class="order-merchant" @click="router.push(`/merchant/${order.merchantId}`)">
              <a-avatar>
                <template #icon><i class="icon-shop"></i></template>
              </a-avatar>
              <span>{{ order.merchantName || `商家${order.merchantId}` }}</span>
              <i class="icon-right"></i>
            </div>
            <div class="order-status" :style="{ color: `var(--color-${getOrderStatusColor(order.status)}-6)` }">
              {{ getOrderStatusText(order.status) }}
            </div>
          </div>
          
          <div class="order-items">
            <div v-if="order.orderItems && order.orderItems.length > 0" 
                 v-for="(item, index) in order.orderItems" 
                 :key="index" 
                 class="order-item">
              <div class="item-info">
                <span class="item-name">{{ 
                  item.dishName || `菜品${index + 1}` 
                }}</span>
                <span class="item-quantity">x{{ item.quantity }}</span>
              </div>
            </div>
            <div class="order-total" v-if="order.orderItems && order.orderItems.length > 0">
              共{{ order.orderItems.reduce((sum, item) => sum + item.quantity, 0) }}件商品，
              实付：<span class="price">¥{{ order.actualAmount?.toFixed(2) || '0.00' }}</span>
            </div>
            <div class="order-total" v-else>
              实付：<span class="price">¥{{ order.actualAmount?.toFixed(2) || '0.00' }}</span>
            </div>
          </div>
          
          <div class="order-info">
            <p>订单号：{{ order.orderNo || '未知' }}</p>
            <p>下单时间：{{ formatDateTime(order.createTime) }}</p>
            <p>收货地址：{{ order.deliveryAddress || '未设置' }}</p>
            <p v-if="order.payMethod">支付方式：{{ getPayMethodText(order.payMethod) }}</p>
          </div>
          
          <div class="order-actions">
            <a-button
              v-if="order.status === 0"
              type="primary"
              @click="openPaymentDialog(order.orderNo!)"
            >
              立即支付
            </a-button>
            <a-button
              v-if="order.status === 0"
              type="outline"
              status="danger"
              @click="handleCancelOrder(order.orderNo!)"
            >
              取消订单
            </a-button>
            <a-button
              v-if="order.status === 3"
              type="outline"
              @click="router.push(`/merchant/${order.merchantId}`)"
            >
              再来一单
            </a-button>
          </div>
        </a-card>
      </div>
    </a-spin>
    
    <!-- 支付方式选择对话框 -->
    <a-modal
      v-model:visible="paymentVisible"
      title="选择支付方式"
      @cancel="closePaymentDialog"
      @before-ok="handlePayOrder"
    >
      <a-radio-group v-model="selectedPayMethod" direction="vertical">
        <a-radio 
          v-for="option in payMethodOptions" 
          :key="option.value" 
          :value="option.value"
        >
          {{ option.label }}
        </a-radio>
      </a-radio-group>
    </a-modal>
  </div>
</template>

<style scoped>
.order-container {
  padding: 16px;
}

.order-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.order-header h2 {
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.order-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.order-card {
  background-color: var(--color-bg-2);
  border-radius: 8px;
}

.order-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 12px;
  border-bottom: 1px solid var(--color-border);
}

.order-merchant {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.order-status {
  font-weight: bold;
}

.order-items {
  margin-bottom: 12px;
  padding-bottom: 12px;
  border-bottom: 1px solid var(--color-border);
}

.order-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.item-info {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.item-name {
  flex: 1;
}

.item-quantity {
  color: var(--color-text-3);
}

.order-total {
  text-align: right;
  font-size: 14px;
}

.order-total .price {
  font-weight: bold;
  color: #ff4d4f;
}

.order-info {
  margin-bottom: 12px;
  font-size: 14px;
  color: var(--color-text-3);
}

.order-info p {
  margin: 4px 0;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
</style> 